package org.grow.auth.config;

import org.grow.auth.service.PostAuthFailure;
import org.grow.auth.service.PostAuthSuccess;
import org.grow.auth.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.Filter;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xwg
 * @CreateDate: 2022/5/25
 */
@EnableRedisHttpSession
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PostAuthSuccess postAuthSuccess;
    @Autowired
    private PostAuthFailure postAuthFailure;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable();
        http.csrf().disable();
        http.httpBasic().disable();
//        第一步 绑定
        http.formLogin()
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
//                第四步 登录成功

//                .successHandler((request, response, authentication) -> {
//                    System.out.println("登录成功");
//                })
                .successHandler(postAuthSuccess)
                .failureHandler(postAuthFailure);
        http.logout()
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID", "SESSIONID")
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));
//        http.anonymous().disable();
        http.anonymous();
//        1 以下二者都不声明 ：则无任何拦截效果 不论身份认证 不论权限拦截
//        声明permitAll 效果是 身份认证必须有 无权限拦截
//        声明authenticated 效果是 既有身份认证，也有权限拦截
        http.authorizeRequests().anyRequest().permitAll();
//        http.authorizeRequests().anyRequest().authenticated();
        http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
            response.setStatus(401);
            response.getWriter().println("生产环境不允许匿名用户登录");
        });
//        http.exceptionHandling().authenticationEntryPoint(new BasicAuthenticationEntryPoint());

    }

    //2查询 根据用户名取数据库查询出信息
    @Autowired
    private UserInfoService userInfoService;

    @Override
    protected UserDetailsService userDetailsService() {
        return userInfoService;
    }

    //    3比较
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
//        return new BCryptPasswordEncoder();
    }
}
